<script setup>
import GetMap from "src/utils/GetMap.js";
import {ROAD_CONTROL} from "src/constant/data.js";
import {useRoadStore} from "stores/road.js";
import {onMounted,ref} from "vue";
import RoadPanel from "components/road/RoadPanel.vue";
import {getRoadInfo} from "src/utils/GetOnePath.js";




let map;
let markerLayer;
let roadLayer;
let startId=null;
let endId=null;
let middleId=[];
let middleCount=0;
let roadStore=useRoadStore();




onMounted(() => {
    map = GetMap(ROAD_CONTROL);
    markerLayer=L.layerGroup().addTo(map);
    roadLayer=L.geoJSON().addTo(map);
    map.on('pm:create', function(e) {
        let layer = e.layer;
      layer.bindPopup("未确定位置");
      layer.on('contextmenu', function(event) {
        const createButton = (text, bgColor, onClick) => {
          const button = document.createElement('button');
          button.style.backgroundColor = bgColor;
          button.style.color = 'white';
          button.textContent = text;
          button.style.width = '100%';
          button.style.height = '40px';
          button.style.marginTop = '10px';
          button.onclick = onClick;
          return button;
        };

        const popupContent = document.createElement('div');
        popupContent.style.width = '100px';
        popupContent.style.height = '150px';

        const startButton = createButton('设为起点', 'blue', () => startAction(layer._leaflet_id));
        const middleButton = createButton('设为途经点', 'green', () => middleAction(layer._leaflet_id));
        const endButton = createButton('设为终点', 'red', () => endAction(layer._leaflet_id));

        popupContent.appendChild(startButton);
        popupContent.appendChild(middleButton);
        popupContent.appendChild(endButton);

        L.popup()
          .setLatLng(event.latlng)
          .setContent(popupContent)
          .openOn(map);
      });
      markerLayer.addLayer(layer);
    });
  }
)
const startAction = (layerId) => {
  // 关闭弹窗
  map.closePopup();
  if (startId) {
    let startMarker=markerLayer.getLayer(startId)
    startMarker.setIcon(L.icon({
      iconUrl: 'marker/marker-icon-2x.png',
      iconSize: [25, 41],
      shadowUrl: 'marker/marker-shadow.png',
      shadowSize: [58, 95],
      shadowAnchor: [22, 94]
    }));
    startMarker.bindPopup("未确定位置");
  }
  startId = layerId;
  // 显示起点
  let marker=markerLayer.getLayer(startId)
  marker.setIcon(L.icon({
    iconUrl: 'marker/Start.png',
    iconSize: [40, 40],
  }));
  marker.bindPopup("<div style='font-size:14px;color:blue;'>起点</div>");

};
const middleAction = (layerId) => {
    // 关闭弹窗
    map.closePopup();
  let marker=markerLayer.getLayer(layerId)
  if(marker.options.isMiddle){
    console.log("middle")
    return ;
  }
  if (middleId.includes(layerId)) {
      markerLayer.getLayer(layerId).bindPopup("未确定位置");
      middleId.splice(middleId.indexOf(layerId), 1);
    }
    else {
      middleId.push(layerId);
      let marker=markerLayer.getLayer(layerId)
      marker.options.isMiddle = true;
      marker.setIcon(L.icon({
        iconUrl: 'marker/Middle.png',
        iconSize: [40, 40],
      }));

      marker.bindPopup(`<div style='font-size:14px;color:orange;'>${middleCount+1}号途径点</div>`);
      middleCount++;
    }
};
const endAction = (layerId) => {
  // 关闭弹窗
  map.closePopup();
  if (endId) {
    markerLayer.getLayer(endId).bindPopup("未确定位置");
  }
  endId = layerId;
  // 显示终点
  let marker=markerLayer.getLayer(endId)
  marker.setIcon(L.icon({
    iconUrl: 'marker/End.png',
    iconSize: [40, 40],
  }));
  marker.bindPopup("<div style='font-size:14px;color:red;'>终点</div>");
};

const send = async () => {
  roadLayer.clearLayers();
  let allLayers = markerLayer.getLayers();
  let startMarkerLatLng;
  let endMarkerLatLng;
  let path;
  let middleMarkerLatLng;
  allLayers.forEach(layer => {
    let layer_id = layer._leaflet_id;
    if (layer_id === startId) {
      startMarkerLatLng = layer.getLatLng();
    }
    if (layer_id === endId) {
      endMarkerLatLng = layer.getLatLng();
    }
  })
  if (!startId || !endId) {
    alert("请设置起点和终点");
    return;
  }
  if (middleId.length === 0) {
    path = await getRoadInfo(startMarkerLatLng, endMarkerLatLng, roadStore.type);
    if (path.status !== 200) {
      alert("路径查询失败");
      return;
    }
    roadLayer.addData(path.data.data);
  }
  for (let i = 0; i < middleCount; i++) {
    let layer_id = middleId[i];
    //最后一个途径点
    if (i === middleCount - 1) {
      middleMarkerLatLng = markerLayer.getLayer(layer_id).getLatLng();
      path = await getRoadInfo(middleMarkerLatLng, endMarkerLatLng, roadStore.type);
      if (path.status !== 200) {
        alert("路径查询失败");
        return;
      }
      roadLayer.addData(path.data.data);
    }
    middleMarkerLatLng = markerLayer.getLayer(layer_id).getLatLng();
    path = await getRoadInfo(startMarkerLatLng, middleMarkerLatLng, roadStore.type);
    if (path.status !== 200) {
      alert("路径查询失败");
      return;
    }
    roadLayer.addData(path.data.data);
  }
  let allData=path.data.data

  allData.features.forEach(feature => {
    roadStore.properties.push(feature.properties)
  })



}
const clear = () => {
  markerLayer.clearLayers();
  roadLayer.clearLayers();
  roadStore.properties=[]
  roadStore.type=null
  startId=null;
  endId=null;
  middleId=[];
}
</script>

<template>
  <div id="map">
    <q-btn color="primary" class="query" @click="send">
      查询
    </q-btn>
    <q-btn color="deep-orange" class="query1" @click="clear">
      清空
    </q-btn>
    <RoadPanel class="query-panel"></RoadPanel>
  </div>
</template>

<style scoped>
.query {
  max-width: 100px;
  width: 10%;
  position: absolute;
  top: 20px;
  right: 10px;
  z-index: 1002;
}
.query1 {
  max-width: 100px;
  width: 10%;
  position: absolute;
  top: 20px;
  right: 150px;
  z-index: 1002;
}
.query-panel {
  position: absolute;
  top: 50px;
  right: 1px;
  z-index: 1002;
}
.delete-button {
  background-color: #f44336;
  text-color: blue;
  border: none;
  border-radius: 10px;
  padding: 4px 8px;
  cursor: pointer;
}
</style>
